package com.ruoyi.app.config.interceptor;


import com.ruoyi.app.business.login.LoginBusiness;
import com.ruoyi.app.config.annotation.ExcludeLoginVerify;
import com.ruoyi.app.config.properties.WhiteUriProperties;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import javax.annotation.Nonnull;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Description: 用户登录拦截器
 */
@Slf4j
@Component
public class AuthenticateInterceptor implements HandlerInterceptor {

  @Resource
  private LoginBusiness loginBusiness;

  @Override
  public boolean preHandle(@Nonnull HttpServletRequest request,
      @Nonnull HttpServletResponse response, @Nonnull Object handler) throws Exception {
    if (handler instanceof HandlerMethod) {
      final HandlerMethod handlerMethod = (HandlerMethod) handler;
      //      final Class<?> clazz = handlerMethod.getBeanType();
      //      final Method method = handlerMethod.getMethod();
      final String url = request.getRequestURI();
      // 跳过不需要验证的路径
      if (StringUtils.matches(url, SpringUtils.getBean(WhiteUriProperties.class).getWhites())) {
        return true;
      }
      //            if (clazz.isAnnotationPresent(ExcludeLoginVerify.class) || method.isAnnotationPresent(ExcludeLoginVerify.class)) {
      //                return true;
      //            }
      final ExcludeLoginVerify excludeLoginVerify = handlerMethod.getMethodAnnotation(
          ExcludeLoginVerify.class);
      if (excludeLoginVerify != null) {
        //获得可用用户信息,特殊接口游客可用情况下
                if (excludeLoginVerify.ctxAvailableUser()) {
                  try {
                    loginBusiness.checkTokenBuildContext(request);
                  } catch (Throwable e) {
                    //swallow 异常
                  }
                }
        return true;
      }
      //验证并处理Token信息
      loginBusiness.checkTokenBuildContext(request);
      return true;
    }
    return true;
  }
}
